package internal

import (
	"github.com/name5566/leaf/gate"
	"server/msg"
	"github.com/name5566/leaf/log"
	"server/mLog"
)

var (
	players map[int32]gate.Agent
)

func init() {
	skeleton.RegisterChanRPC("NewAgent", rpcNewAgent)
	skeleton.RegisterChanRPC("CloseAgent", rpcCloseAgent)
	skeleton.RegisterChanRPC("UserLogin", rpcUserLogin)
	skeleton.RegisterChanRPC("CreatePlayer", rpcCreatePlayer)
}

func rpcNewAgent(args []interface{}) {
}

func rpcCloseAgent(args []interface{}) {
	a := args[0].(gate.Agent)

	var leaveId int32

	var room = &Room{}

	for _, val := range playerID2Player {
		if val.Agent == a {
			leaveId = val.playerBaseInfo.PlayerID
			room = val.room
		}
	}

	mLog.Println("rpcCloseAgent")
	delete(playerID2Player, leaveId)

	if room == nil {
		return
	}

	delete(room.roomPlayers, leaveId)

	for _, p := range room.roomPlayers {
		p.WriteMsg(&msg.LeaveRoom{
				PlayerId: leaveId,
		})
	}
}

func rpcUserLogin(args []interface{}) {
	agent := args[0].(gate.Agent)
	playerID := args[1].(int32)

	oldUser := playerID2Player[playerID]
	if oldUser != nil {
		m := &msg.LoginFaild{Code: msg.LoginFaild_LoginRepeat}
		agent.WriteMsg(m)
		oldUser.WriteMsg(m)
		agent.Close()
		oldUser.Close()
		log.Debug("acc %v login repeated", playerID)
		return
	}
	log.Debug("acc %v login", playerID)

	newPlayer := new(Player)
	newPlayer.Agent = agent
	newPlayer.LinearContext = skeleton.NewLinearContext()
	newPlayer.state = userLogin
	newPlayer.login(playerID)
}

func rpcCreatePlayer(args []interface{}) {
	agent := args[0].(gate.Agent)
	playerID := args[1].(int32)
	err := CreatePlayer(playerID)
	if nil != err {
		m := &msg.LoginFaild{Code: msg.LoginFaild_InnerError}
		agent.WriteMsg(m)
	}

}
